package com.richper.springcloudh2020.controller;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@RestController
public class HystrixPaymentController {
    @GetMapping("/id")
    public String getId(){
        return "8006";
    }

    @GetMapping("/payment_ok")
    public String payment_ok(){
        return "线程池："+Thread.currentThread().getName()+"  payment_ok,O(∩_∩)O";
    }

    @GetMapping("/payment_timeOut")
    @HystrixCommand(fallbackMethod = "payment_timeOutHandler",commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "5000")
    })
    public String payment_timeOut(){
        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "线程池："+Thread.currentThread().getName()+"  payment_TimeOut,耗时（秒）：3,  O(∩_∩)O";
    }

    public String payment_timeOutHandler(){
        return "线程池："+Thread.currentThread().getName()+"  8006系统忙，请稍后再试。,  ┭┮﹏┭┮";
    }

    //================服务熔断========华丽的分割线========服务熔断==================

    @GetMapping("/div/{id}")
    @HystrixCommand(fallbackMethod = "divFuse",commandProperties = {
            @HystrixProperty(name = "circuitBreaker.enabled",value = "true"),//开启断路器，默认为false
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "10"),// 时间范围内请求次数
            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds",value = "10000"),//时间范围
            @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage",value = "60")//时间范围内达到60%的错误率
    })
    //================注释========华丽的分割线========注释==================
    //10秒范围内10次请求达到60%的错误率，断路器从关闭状态更改为打开状态，
    // 在下一个时间范围内，尝试着通过一个请求，看服务是否恢复，如果没有恢复，则还是打开状态，
    //  如果恢复了，则关闭断路器，恢复服务调用链
    public String div(@PathVariable("id") int id){
        if (id <= 0){
            throw new RuntimeException("ID不能为0");
        }
        int i = 100 / id;
        return Thread.currentThread().getName()+" -> IdUtil.simpleUUID() ：100 ➗ "+id+" = "+i;
    }

    public String divFuse(int id){
        return Thread.currentThread().getName()+" ：8006服务异常请稍后再试...id不能为0";
    }
}
